import pandas as pd
import warnings
warnings.filterwarnings("ignore")

# 1. 数据加载
train = pd.read_csv("file/train.csv")
test = pd.read_csv("file/test.csv")

print(train.info())
print(test.info())

# 查看空值
print(train.isnull().sum())
print(test.isnull().sum())
# 2. 数据预处理
#  特征类型转换
train['Vehicle_Damage'] = train['Vehicle_Damage'].map({'Yes':1, 'No':0})
test['Vehicle_Damage'] = test['Vehicle_Damage'].map({'Yes':1, 'No':0})

vehicle_age_map = {'< 1 Year':0, '1-2 Year':1, '> 2 Years':2}
train['Vehicle_Age'] = train['Vehicle_Age'].map(vehicle_age_map)
test['Vehicle_Age'] = test['Vehicle_Age'].map(vehicle_age_map)

train['Gender'] = train['Gender'].map({'Male':1, 'Female':0})
test['Gender'] = test['Gender'].map({'Male':1, 'Female':0})

# 特征筛选（删除id）
x_train = train.drop(['id', 'Response'], axis=1)
y_train = train['Response']
x_test = test.drop(['id'], axis=1)

# 3. 模型训练（以XGBoost为例）
from xgboost import XGBClassifier

# 模型训练与评估
xgb = XGBClassifier(learning_rate=0.1, n_estimators=100)
xgb.fit(x_train, y_train)

from sklearn.model_selection import GridSearchCV

# 定义要搜索的参数网格
param_grid = {
    'n_estimators': [30, 50, 70],
    'max_depth': [None, 10, 20],
    'subsample': [0.5,0.8,1]
}
# 初始化XGB分类器
xgb = XGBClassifier(random_state=42)

# 使用 GridSearchCV 进行网格搜索
grid_search = GridSearchCV(estimator=xgb, param_grid=param_grid, cv=5)

# 在训练集上进行网格搜索
grid_search.fit(x_train, y_train)

# 输出最优参数组合
print('最优参数组合:', grid_search.best_params_)

# 获取最优模型
best_rf = grid_search.best_estimator_

# 使用最优模型对测试集进行预测
y_pred = best_rf.predict(x_test)
print(y_pred)

# result_df = pd.DataFrame({'id': test['id'], 'Response_prediction': y_pred})
# result_df.to_csv('test_prediction.csv', index=False)

# TODO 客户的投保概率占比0.0008895046325086392